<template>
  <home-header @reset-view="resetView"/>
  <!-- 遮罩层 -->
  <main>
    <div class="cover" ref="cover" v-if="coverShow">
      <el-icon size="30px" color="#fff" @click="closeZoom"><CloseBold /></el-icon>
    </div>
    <el-row>
      <!-- 左侧 -->
      <el-col :span="7" class="left">
        <!-- 饼图-->
        <div class="chart">
          <h3>
            监测点{{ device_currentId}}紫外传感器数据折线图
            <el-icon size="22px" @click="zoom(1)"><FullScreen /></el-icon>
          </h3>
          <div class="chart-item" ref="uvcRef"></div>
          <span class="border_bg_leftTop"></span>
        </div>
        <div class="chart">
          <h3>监测点{{ device_currentId}}红外传感器数据折线图   <el-icon size="22px" @click="zoom(2)"><FullScreen /></el-icon></h3>
          <div class="chart-item" ref="infRef"></div>
          <span class="border_bg_leftTop"></span>
        </div>
        <div class="chart">
          <h3>监测点{{ device_currentId}}振动传感器数据折线图   <el-icon size="22px" @click="zoom(3)"><FullScreen /></el-icon></h3>
          <div class="chart-item" ref="accRef"></div>
          <span class="border_bg_leftTop"></span>
        </div>
      </el-col>
      <!-- 中间 -->
      <el-col :span="10">
        <main class="mainCenter">
          <!--标题-->
          <header class="middle-header">
            <!--首页标题-->
            <div class="title">
              氮化镓紫外局放监测系统
            </div>
            <!--首页描述信息-->
            <div class="description">
              紫外、红外、振动、温度、压力、湿度
            </div>
          </header>
          <!-- 选择模块 -->
          <main class="drawer-main">
            <el-carousel 
            v-if="module_list.length > 6"
            indicator-position="none" 
            :autoplay="false"
            >
              <el-carousel-item class="grid_layout" v-for="item in Math.ceil(module_list.length/6)" :key="item">
                <div class="module_item" v-for="e in module_list.slice((item-1)*6,item*6)" :key="e.id" @click="taggleDevice(e.id)">
                    <div class="img">
                      <img src="../assets/module.active.png" v-if="e.isChecked" />
                      <img src="../assets/module.png" v-else />
                      <p style="margin-top: 10px;color:#e5dc3d;" v-if="e.isChecked">{{ e.deviceName }}</p>
                      <p style="margin-top: 10px;" v-else>{{ e.deviceName }}</p>
                    </div>
                </div>
              </el-carousel-item>
            </el-carousel>
            <div class="grid_layout" v-else>
              <div class="module_item" v-for="e in module_list" :key="e.id" @click="taggleDevice(e.id)">
                    <div class="img">
                      <img src="../assets/module.active.png" v-if="e.isChecked" />
                      <img src="../assets/module.png" v-else />
                      <p style="margin-top: 10px;color:#e5dc3d;" v-if="e.isChecked">{{ e.deviceName }}</p>
                      <p style="margin-top: 10px;" v-else>{{ e.deviceName }}</p>
                    </div>
                </div>
            </div>
        </main>
        </main>
      </el-col>
      <!-- 右侧 -->
      <el-col :span="7" class="right">
        <div class="chart">
          <h3>监测点{{ device_currentId}}温度传感器数据折线图  <el-icon size="22px" @click="zoom(4)"><FullScreen /></el-icon></h3>
          <div class="chart-item" ref="temRef">
          </div>
          <span class="border_bg_leftTop"></span>
        </div>
        <!-- 饼图-->
        <div class="chart">
          <h3>监测点{{ device_currentId}}湿度传感器数据折线图 <el-icon size="22px" @click="zoom(5)"><FullScreen /></el-icon></h3>
          <div class="chart-item" ref="humRef">
          </div>
          <span class="border_bg_leftTop"></span>
        </div>
        <div class="chart">
          <h3>监测点{{ device_currentId}}压力传感器数据折线图<el-icon size="22px" @click="zoom(6)"><FullScreen /></el-icon></h3>
          <div class="chart-item" ref="preRef">
          </div>
          <span class="border_bg_leftTop"></span>
        </div>
      </el-col>
    </el-row>
  </main>
</template>
<script lang="ts" setup>

import {userStore} from "../store/user";
import { moduleStore } from "../store/module"
import { adminStore } from '../store/admin'
import {storeToRefs} from 'pinia'

type obj = {
   orderName: string,
   id: number,
   refName: string
}
  let store = userStore()
  let admin_store = adminStore()
  let module_store = moduleStore()
  // 初始化监测的手机列表
  admin_store.initPhoneList()
  let {localWebsocket} = storeToRefs(store)
  let {device_currentId,module_list,module_num} = storeToRefs(module_store)
  import { IhttpReturn,Imodule,IrunStatus} from "../until/interface"
  import HomeHeader from "../components/common/Header.vue"
  import Tool from '../until/tool'
  import * as echarts from "echarts"
  import { ECharts } from "echarts"
  import {setOption,AccOption} from '../until/chart'
  import {ref,onMounted,reactive,getCurrentInstance, ComponentInternalInstance} from 'vue'
  import { Timer } from "@element-plus/icons-vue";
  let {proxy} = getCurrentInstance() as ComponentInternalInstance

  // 关于紫外的
  let uvcRef= ref()
  let uvcPirture = reactive<ECharts>({} as ECharts) // 紫外折线图对象
  let uvcArr = reactive<Array<number>>([])
  let uvcMax = ref<number>()
  let uvcMin = ref<number>()
 
  // 关于红外的
  let infRef = ref()
  let infPirture = reactive<ECharts>({} as ECharts) // 红外折线图对象
  let infArr = reactive<Array<number>>([])
  let infMax = ref<number>()
  let infMin = ref<number>()

  // 关于振动
  let accRef = ref()
  let accPirture = reactive<ECharts>({} as ECharts) // 振动折线图对象
  let accMin = ref<number>()
  let accMax = ref<number>()
  let accxArr = reactive<Array<number>>([]) // 振动x轴
  let accyArr = reactive<Array<number>>([]) // 振动y轴

  // 关于温度
  let temRef = ref()
  let temPirture = reactive<ECharts>({} as ECharts)  // 温度折线图对象
  let temArr = reactive<Array<number>>([])
  let temMax = ref<number>()
  let temMin = ref<number>()

  // 关于湿度
  let humRef = ref()
  let humArr = reactive<Array<number>>([])
  let humPirture = reactive<ECharts>({} as ECharts) // 湿度折线图对象
  let humMax = ref<number>()
  let humMin = ref<number>()
    
   
  // 关于压力
  let preRef = ref()
  let prePirture = reactive<ECharts>({} as ECharts) // 电压折线图对象
  let preArr = reactive<Array<number>>([])
  let preMax = ref<number>()
  let preMin = ref<number>()

  // 关于折线图x轴
  let xaxisData = reactive<number[]>([])
  let time = ref(0)
  let deviceNameList = ref(['紫外','红外','温度','湿度','压力'])
  
  /**放大和缩小展示 */
  let cover = ref() // 放大全屏遮罩层
  let coverShow = ref<boolean>(false)
  let zoomId = ref<number>(); // 放大id

  // 导入线程模块
  // @ts-ignore
    import sendMsgWorker from '@/worker/sendMsg?worker' // 发送短信的线程
    import saveDataWorker from '@/worker/saveMsg?worker' // 保存数据的线程
    let saveWorker = new saveDataWorker()  // 保存数据
    let sendWorker = new sendMsgWorker() // 发送短信

    // 获取模块的个数
    const getModuleNum = async () => {
      if (!module_num.value) {
        // 发送请求获取模块的个数
        let res = await proxy!.$insideHttp.get("/socket/getModuleNum")
        module_num.value = res.data.data
        //@ts-ignore
        for(let i=1;i<=module_num.value;i++) {
          if (i == 1) {
              //@ts-ignore
              module_list.value.push({
                id: 1,
                deviceName: "监测点1",
                isChecked: true
              })
          } else {
              //@ts-ignore
            module_list.value.push({
                id: i,
                deviceName: "监测点"+i,
                isChecked: false
              })
          }
        }
        module_store.initModuleList()
      }
    }

  // 重置视图
  const resetView = (argId:number | undefined) => {
    if (typeof argId === 'undefined') {
      setTimeout(() => {
        uvcPirture.resize()
        infPirture.resize()
        humPirture.resize()
        temPirture.resize()
        prePirture.resize()
        accPirture.resize()
      }, 300);
       
    } else {
      switch (argId) {
        case 1: uvcPirture.resize();break;
        case 2: infPirture.resize();break;
        case 3: accPirture.resize();break;
        case 4: temPirture.resize();break;
        case 5: humPirture.resize();break;
        case 6: prePirture.resize();break;
      }
    }
  }
  // 关闭放大
   let closeZoom = () => {
    let panels = document.querySelectorAll(".chart")
    proxy.$nextTick(() => {
      let currentRef = orderList[zoomId.value - 1].refName
      coverShow.value = false
      panels[zoomId.value - 1].appendChild(eval(`${currentRef}.value`))
      resetView(zoomId.value)
      Tool.tool.len = 8
    })
  }
  // 放大
  let zoom = (id:number|undefined) => {
      zoomId.value = id
      coverShow.value = true
      Tool.tool.len = 10
      let currentDevice:string | undefined = orderList[id- 1].refName // 获取设备的引用
      console.log(currentDevice)
      let currentDom:HTMLElement = eval(`${currentDevice}.value`) // 获取当前的设备元素
      currentDom.style.height = "100%"
      proxy.$nextTick(() => {
            cover.value.appendChild(currentDom)
            resetView(id)
        })
  }
  // 放大的设备列表
  const orderList:Array<obj> = [
    {
      orderName: "紫外",
      id: 1,
      refName: "uvcRef"
    },
    {
      orderName: "红外",
      id: 2,
      refName: "infRef"
    },
    {
      orderName: "振动",
      id: 3,
      refName: "accRef"
    },
    {
      orderName: "温度",
      id: 4,
      refName: "temRef"
    },  {
      orderName: "湿度",
      id: 5,
      refName: "humRef"
    },
    {
      orderName: "压力",
      id: 6,
      refName: "preRef"
    }
  ]
  const isShowTip = ref(true) // 是否提醒用户报警信息
  // 生命周期
  onMounted(async () => {
    proxy!.$insideHttp.get("/socket/addRunDate")
    getModuleNum()
    // 初始化websocket
    initWebsocket()
    // 初始化各个传感器的参数
    initEchart()
    render()

      // 调节屏幕的尺寸
      window.onresize = function() {
        let clientWidth = document.body.clientWidth
        resetView()
        if (clientWidth <1400) {
          Tool.tool.len = 6
        } else if (clientWidth > 1500) {
          Tool.tool.len = 8
        }
      }

      // 判断程序是否在后台运行 => 优化项目
      window.addEventListener("visibilitychange",() => {
          if (document.hidden) {
            // 在后台运行项目
            isShowTip.value = false
            console.log("在后台运行")
          } else {
            // 在前台运行项目
            isShowTip.value = true
            console.log("在前台运行")
          }
      })
  })


    // 初始化传感器
  const initEchart = () => {
      uvcPirture = echarts.init(uvcRef.value)
      infPirture = echarts.init(infRef.value)
      temPirture = echarts.init(temRef.value)
      prePirture = echarts.init(preRef.value)
      humPirture = echarts.init(humRef.value)
      accPirture = echarts.init(accRef.value)
    }
    // 统计设备的报警状态
    let totalStatus = {
       warning: {
        info: []
       },
       error: {
        info: []
       }
    }
    const countNormal = (obj:any,id:number) => {
      for(let i=0;i<5;i++) {
        if (obj[i] === 0) {
        } else if (obj[i] === 1) {
          totalStatus.warning.info.push(`监测点${id}的${deviceNameList.value[i]}`)
        } else {
         if (admin_store.isAableSendMsg) {
            // 发送短信进行提醒用户
            //@ts-ignore
            sendWorker.postMessage(JSON.stringify({
              // @ts-ignore
              phoneList: admin_store.phoneList.filter(item => item.isWatch),
              module_id: id,
              type: i
            }))
         }
         totalStatus.error.info.push(`监测点${id}的${deviceNameList.value[i]}`)
        }
      }
      if (id == module_num.value) {
          if (totalStatus.warning.info.length > 0) {
              // 发生了警告
              if (isShowTip.value) {
                proxy.$message({
                  message: `${totalStatus.warning.info.join(",")}的数值偏高，请注意查看。`,
                  type: "warning",
                  duration: 1200
              })
              }
        }  
        if (totalStatus.error.info.length > 0) {
              // 发生了报警
              if (isShowTip.value) {
                  proxy.$message({
                  message: `${totalStatus.error.info.join("，")}的数值异常，请检查设备。`,
                  type: 'error',
                  duration: 1200
                })
              }
            
        } 
        // 重新清空统计
        totalStatus.error.info = []
        totalStatus.warning.info = []
      }
    } 
    // 切换设备
   const taggleDevice = (id:number) => {
	      device_currentId.value = id
        time.value = 0
        infArr = []
        uvcArr = []
        preArr = []
        humArr = []
        temArr = []
        accxArr = []
        accyArr = []
        xaxisData = []
        module_list.value.forEach(item => item.isChecked = false)
        module_list.value[id - 1].isChecked = true
        proxy.notifySuccess("切换到"+ module_list.value[id-1].deviceName)
    }

    /**渲染部分 */
    const render = async () => {
      try {
        // @ts-ignore
        localWebsocket.value.onmessage = async (msg) => {
            let device_data = JSON.parse(msg.data)
            if (store.deviceList.length >= 2) {
              // @ts-ignore
              store.websocket.send(
                  JSON.stringify({
                  action: "sendData",
                  token:store.userInfo.token,
                  linkCode: store.linkCode,
                  data: Object.assign({runTime: new Date().getTime(),speed: store.speed,module_num: module_num.value},device_data)
                }))
            }
            if (device_currentId.value == device_data.ID.id) {
              let uvc_val = device_data.uvc.uv_ave  
              time.value ++ 
                uvcArr = Tool.tool.limitArrayLength(uvcArr,uvc_val)
                infArr = Tool.tool.limitArrayLength(infArr,device_data.ir.max)
                preArr = Tool.tool.limitArrayLength(preArr,device_data.pressure.pre)
                humArr = Tool.tool.limitArrayLength(humArr,device_data.humidity.hum)
                temArr = Tool.tool.limitArrayLength(temArr,device_data.temperature.temp)
                accxArr = Tool.tool.limitArrayLength(accxArr,0)
                accyArr = Tool.tool.limitArrayLength(accyArr,0)
                // 获取振动的量程
                accMin.value = Math.min.apply(Math,[Tool.tool.getMinValue(accxArr),Tool.tool.getMinValue(accyArr)]) - 1
                accMax.value = Math.min.apply(Math,[Tool.tool.getMaxValue(accxArr),Tool.tool.getMaxValue(accyArr)]) + 1

                //紫外的量程
                uvcMax.value = Tool.tool.getMaxValue(uvcArr)
                uvcMin.value = Tool.tool.getMinValue(uvcArr)

                // 获取压力的量程
                preMax.value = Tool.tool.getMaxValue(preArr)
                preMin.value = Tool.tool.getMinValue(preArr)
                // 获取湿度的量程
                humMax.value = Tool.tool.getMaxValue(humArr)
                humMin.value = Tool.tool.getMinValue(humArr)
                // 获取温度的量程
                temMin.value = Tool.tool.getMinValue(temArr)
                temMax.value = Tool.tool.getMaxValue(temArr)
                // 获取红外的量程
                infMin.value = Tool.tool.getMinValue(infArr)
                infMax.value = Tool.tool.getMaxValue(infArr)
                xaxisData = Tool.tool.limitArrayLength(xaxisData,time.value)
                // 渲染数据
                renderPirture()
             }
             
          let uvc_sta = device_data.uvc.uvc_sta
          let ir_sta = device_data.ir.ir_sta
          let temp_sta = device_data.temperature.temp_sta
          let hum_sta = device_data.humidity.hum_sta
          let pre_sta = device_data.pressure.pre_sta
          countNormal([uvc_sta,ir_sta,temp_sta,hum_sta,pre_sta],device_data.ID.id)  

          // // 保存数据
          // saveWorker.postMessage(JSON.stringify({
          //     module_id: device_data.ID.id,
          //     uvc: uvc_val,
          //     inf: device_data.ir.max,
          //     tem: device_data.temperature.temp,
          //     hum: device_data.humidity.hum,
          //     pre: device_data.pressure.pre,
          //     uvc_sta,
          //     ir_sta,
          //     temp_sta,
          //     hum_sta,
          //     pre_sta
          //  }))
 
        }
        } catch(err) {
            console.log(err)
        }
    }
    // 渲染视图
    const renderPirture = () => {
        uvcPirture.setOption(setOption("紫外光","#ffaaff",xaxisData,uvcArr, uvcMin.value,uvcMax.value));
        temPirture.setOption(setOption("温度/℃","#c30720",xaxisData,temArr,temMin.value,temMax.value));
        prePirture.setOption(setOption("压力/Kpa","#ffba00",xaxisData,preArr,preMin.value,preMax.value));
        humPirture.setOption(setOption("湿度/%RH","#00ffa2",xaxisData,humArr,humMin.value,humMax.value));
        infPirture.setOption(setOption("红外/℃","#34d1fd",xaxisData,infArr,infMin.value,infMax.value))
        accPirture.setOption(AccOption(["振动x轴","振动y轴"],["#ED4C67","#9980FA"],xaxisData,[accxArr,accyArr],accMin.value,accMax.value ))
    }

    // 建立websocket连接
    const initWebsocket = () => {
      // @ts-ignore
      localWebsocket.value = new WebSocket("ws://localhost:6677")
        // @ts-ignore
        localWebsocket.value.onopen = function() {
            console.log("本地连接已经打开")
          }
          // @ts-ignore
          localWebsocket.value.onclose = function() {
            console.log("断开连接")
            initWebsocket()
          }
    
    }

</script>
<style scoped lang="less">
main {
  padding: 20px 10px;
  height: calc(100% - 80px);
}
  @keyframes rotating {
    0%{
      transform: translate(-50%, -50%) rotateY(0deg);
    }
    100%{
      transform: translate(-50%, -50%) rotateY(360deg);
    }
  }

  // 定义动画类
  .animateCss {
        animation-name: rotating;
        animation-duration: 16s;
        animation-timing-function: linear;
        animation-iteration-count: infinite;
        animation-play-state: running;
  }
  .animateCss1 {
        animation-name: rotating;
        animation-duration: 16s;
        animation-timing-function: linear;
        animation-iteration-count: infinite;
        animation-play-state: running;
  }

  .cover {
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 999;
    background:#1d335d;
    .el-icon {
      position: absolute;
      z-index: 9999;
      top:0;
      right: 0;
    }
  }
.el-row {
  height: 100%;

  .left {
    display: flex;
    flex-direction: column;
    height: 100%;
  }
  .right {
    display: flex;
    flex-direction: column;
    height: 100%;
  }
}
  .chart {
    width: 100%;
    flex: 1;
    padding-left: 5px;
    border: 0.008rem solid rgba(14,253,255,0.5);
    position: relative;
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
    .chart-item {
       flex: 1;
      padding-bottom: 5px;
    }
    &:last-child {
      margin-bottom: 0px;
    }
    h3 {
      font-size: 20px;
      color: #fff;
      height: 50px;
      line-height: 50px;
      position: relative;
      .el-icon {
        position: absolute;
        top: 5px;
        right: 0;
      }
    }
    .border_bg_leftTop {
      position: absolute;
      left: -0.008rem;
      top: -0.04rem;
      width: 0.37rem;
      height: 0.05rem;
      display: block;
      background: #29292f url("../assets/images/title_left_bg.png") no-repeat;
      background-size: cover;
    }
  }
  .middle-header {
    .title {
      width: 100%;
      text-align: center;
      color: rgb(46, 192, 246);
      font-size: 40px;
      height: 70px;
      line-height: 70px;
    }
    .description {
      color: rgb(255, 255, 255);
      font-size: 20px;
      height: 30px;
      line-height: 30px;
      text-align: center;
    }
  }
  .mainCenter {
    width: 100%;
    height: 100%;
    position: relative;
    // 动画样式
    .rotate-container {
      height: 46%;
      width: inherit;
      perspective: 1000px;
      position: absolute;
      z-index: 1;
      transform: rotateX(-10deg) rotateY(0deg);
      #spin-animate {
        position: absolute;
        width: 170px;
        height: 180px;
        top: calc(100% - 80px);
        left: 50%;
        transform: translate(-50%, -50%);
        transform-style: preserve-3d;
  
        img {
          position: absolute;
          top: 0;
          left: 0;
          z-index: 88;
          transition: all 0.3s;
          width: 66%;
          box-shadow: 0 0 8px #fff;
          height: 100%;
          &:nth-child(1) {
            transform: rotateY(72deg) translateX(228px) rotateY(90deg);
          }
          &:nth-child(2) {
            transform: rotateY(144deg) translateX(228px) rotateY(90deg);
          }
          &:nth-child(3) {
            transform: rotateY(216deg) translateX(228px) rotateY(90deg);
          }
          &:nth-child(4) {
            transform: rotateY(288deg) translateX(228px) rotateY(90deg);
          }
          &:nth-child(5) {
            transform: rotateY(360deg) translateX(228px) rotateY(90deg);
          }
        }
      }
    }
     // 人物样式
    .personAvatar {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%,-50%);
      z-index: 0;
      width:70%;
      height: 800px;
    }
  }
   // 收益明细
   #income {
      ul {
        height: 100%;
        display: grid;
        grid-template-rows: repeat(2,1fr);
        grid-template-columns: repeat(3,1fr);
        list-style: none;
        gap: 5px 10px;
        li {
          div {
            font-size: 30px;
            color: rgba(14,253,255,1);
            font-family: dig;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: normal;
          }
          p {
            color: #fff;
            font-size: 16px;
            text-align: center;
          }
        }
      }
   }

.drawer-main {
  padding: 60px 0;
  width: 100%;
  height: 500px;
  .el-carousel {
      width: 100%;
      height: 100%;
      :deep(.el-carousel__container) {
        height: 100%!important;
      }
     :deep(.el-carousel__arrow) {
       transform: scale(1.1);
       background: rgba(186, 186, 186, 0.4);
      }
    }
    .grid_layout {
        width: 100%;
        height: 100%;
        display: grid;
        grid-template-rows: repeat(2,1fr);
        grid-template-columns: repeat(3,1fr);
      }
  .module_item {
    display: flex;
    justify-content: center;

    .img {
      width: 150px;
      height: 150px;
      border-radius: 50%;
      border: 1px solid #d6d4d4;
      background:  url("../assets/contentBg.png") no-repeat center;
      justify-content: center;
      align-items: center;
      box-shadow: 6px 2px 18px rgba(0,0,0,.7);
      display: flex;
      flex-direction: column;
      img {
        width: 50px;
        height: 50px;
      }
      p {
      width: 100%;
      text-align: center;
      color: #fff;
    }
    }
  
  }
}
/**激活模块高亮 */
.activeModule {
  border: 10px solid #d6d4d4;
}
</style>